#include "adc.h"
#include "gpio.h"
#include "bgr.h"
#include "adc_api.h"
#include "uart_api.h"

volatile uint32_t u32AdcRestult;
int8_t adc_finish_flag = 0;

///< ADC 中断服务程序
void Adc_IRQHandler(void)
{    
    if(TRUE == Adc_GetIrqStatus(AdcMskIrqSgl))
    {
        Adc_ClrIrqStatus(AdcMskIrqSgl);       ///< 清除中断标志位
        
        u32AdcRestult = Adc_GetSglResult();   ///< 获取采样值
        adc_finish_flag = 1;
        Adc_SGL_Stop();                       ///< ADC 单次转换停止
    }
}

float get_batteryVal(void)
{
     float batteryVal = 0;
     ///< 启动单次转换采样
     Adc_SGL_Start();
     while (adc_finish_flag != 1);//等待转换完成
	adc_finish_flag = 0;
     batteryVal = (u32AdcRestult/4095.0)*2.5;
     Debug_Printf("adcVal: %f, batteryVal: %f", u32AdcRestult, batteryVal);
     return batteryVal*2;//实际电压
}

void adc_battery_init(void)
{
     ///< 开启ADC/BGR GPIO外设时钟
     Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE);
    
     Gpio_SetAnalogMode(GpioPortA, GpioPin0);        //PA00 (AIN0)

     stc_adc_cfg_t stcAdcCfg;

     DDL_ZERO_STRUCT(stcAdcCfg);
     Sysctrl_SetPeripheralGate(SysctrlPeripheralAdcBgr, TRUE); 
     Bgr_BgrEnable();        ///< 开启BGR
     ///< ADC 初始化配置
     stcAdcCfg.enAdcMode         = AdcSglMode;              ///<采样模式-单次
     stcAdcCfg.enAdcClkDiv       = AdcMskClkDiv8;            ///<采样分频-2
     stcAdcCfg.enAdcSampCycleSel = AdcMskSampCycle12Clk;      ///<采样周期数-12
     stcAdcCfg.enAdcRefVolSel    = AdcMskRefVolSelInBgr2p5;      ///<参考电压选择
     stcAdcCfg.enAdcOpBuf        = AdcMskBufDisable;         ///<OP BUF配置-关
     stcAdcCfg.enInRef           = AdcMskInRefEnable;       ///<内部参考电压使能-关
     stcAdcCfg.enAdcAlign        = AdcAlignRight;            ///<转换结果对齐方式-右
     Adc_Init(&stcAdcCfg);
     ///< ADC 采样通道配置
     Adc_CfgSglChannel(AdcExInputCH0);
    
     ///< ADC 中断使能
     Adc_EnableIrq();
     EnableNvic(ADC_IRQn, IrqLevel3, TRUE);
    

}


